package com.googlecode.imanager.client.form;

import com.googlecode.imanager.client.Application;
import com.googlecode.imanager.client.Container;
import com.googlecode.imanager.client.Control;
import com.googlecode.imanager.client.Focusable;
import com.googlecode.imanager.client.bridge.IFocusable;
import com.googlecode.imanager.client.util.ControlState;
import com.googlecode.imanager.client.util.Utils;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public abstract class FocusControl extends Control implements IFocusable, Focusable {

    private static final long serialVersionUID = 1L;
    
    private Integer tabIndex;
    private Character accessKey;
    
    public FocusControl() {
        super();
    }

    protected FocusControl(int width, int height) {
        super(width, height);
    }

    protected void onFocus(){
        addState(ControlState.FOCUSED);
    }
    
    protected void onBlur(){
        removeState(ControlState.FOCUSED);
    }
    
    @Override
    protected void onBeforeSetParent(Container newParent) {
        super.onBeforeSetParent(newParent);
        Application app = getApplication();
        if (app != null
                && app.getFocusControl() == this){
            app.setFocusControl(null);
        }
    }

    public void focus(){
        Application app = getApplication();
        if (app != null){
            app.setFocusControl(this);
        }
    }

    public void blur(){
        Application app = getApplication();
        if (app != null
                && app.getFocusControl() == this){
            app.setFocusControl(null);
        }
    }

    @Override
    public void transferFocusBackward() {
        getBridge().transferFocusBackward();
    }

    @Override
    public void transferFocusForward() {
        getBridge().transferFocusForward();
    }

    @Override
    public boolean isFocused() {
        Application app = getApplication();
        return app != null && app.getFocusControl() == this;
    }

    public Integer getTabIndex() {
        return tabIndex;
    }

    public void setTabIndex(Integer tabIndex) {
        if (Utils.isEquals(this.tabIndex, tabIndex)){
            this.tabIndex = tabIndex;
            getBridge().setTabIndex(tabIndex);
        }
    }

    public Character getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(Character accessKey) {
        if (!Utils.isEquals(this.accessKey, accessKey)){
            this.accessKey = accessKey;
            getBridge().setAccessKey(accessKey);
        }
    }

    @Override
    public FocusControl clone() {
        return (FocusControl) super.clone();
    }

    @Override
    protected IFocusable getBridge() {
        return (IFocusable) lookupBridge();
    }

}
